package com.ruibei.ui.adapter;

import java.util.List;

import com.ruibei.R;
import com.ruibei.models.SortModel;
import com.ruibei.utils.BaseViewHolder;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;


public class SortAdapter extends BaseAdapter implements SectionIndexer {
	private List<SortModel> mList = null;
	private Context mContext;

	// private Bitmap bitmap;

	public SortAdapter(Context mContext, List<SortModel> list) {
		this.mContext = mContext;
		this.mList = list;
	}

	public void updateListView(List<SortModel> list) {
		mList = list;
		notifyDataSetChanged();
	}

	public int getCount() {
		return mList==null?0:mList.size();
	}

	public SortModel getItem(int position) {
		return mList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		if(convertView == null){
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.list_item_contact, parent, false);
		}
		TextView tvLetter = BaseViewHolder.get(convertView, R.id.catalog);
		TextView tvName = BaseViewHolder.get(convertView, R.id.contact_name);
		
		SortModel sortModel = getItem(position);
		
		int section = getSectionForPosition(position);
		if (position == getPositionForSection(section)) {
			tvLetter.setVisibility(View.VISIBLE);
			tvLetter.setText("" + sortModel.getSortLetters());
		} else {
			tvLetter.setVisibility(View.GONE);
		}
		
		tvName.setText(sortModel.getName());
		
		return convertView;
	}


	public int getSectionForPosition(int position) {
		return mList.get(position).getSortLetters().charAt(0);
	}

	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = mList.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}

		return -1;
	}

	private String getAlpha(String str) {
		String sortStr = str.trim().substring(0, 1).toUpperCase();
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}

	@Override
	public Object[] getSections() {
		return null;
	}
}